var express = require('express');
var router = express.Router();
var uuid = require('uuid').v1;


router.get('/key', async function (req, res, next) {
    var projectId = req.query.projectId;
    var Sql = `SELECT * FROM project_custom_key WHERE project_id = ? AND disable = 0`;
    try {
        var vals = await asyncQuery(Sql, [projectId]);
        res.json(vals);
    } catch (error) {
       next(error)
    };
});

router.post('/key', async function (req, res, next) {
    var customKeyId = uuid();
    var data = {
        custom_key_id: customKeyId,
        project_id: req.body.projectId,
        key: req.body.key,
        disable: 0,
    };

    var Sql = `INSERT INTO project_custom_key SET ?`;
    try {
        await Permission.CPP(req.headers.token,  req.query.projectId);
        await asyncQuery(Sql, data);
        res.json({
            id: customKeyId
        });
    } catch (error) {
       next(error)
    };
})


router.put('/key', async function (req, res, next) {
    var customKeyId = req.body.customKeyId;
    var data = {
        key: req.body.key,
    };

    var Sql = `UPDATE project_custom_key SET ? WHERE custom_key_id = ?`;
    try {
        await Permission.CPP(req.headers.token,  req.query.projectId);
        await asyncQuery(Sql, [data, customKeyId]);
        res.json({});
    } catch (error) {
       next(error)
    };
});


router.delete('/key', async function (req, res, next) {
    var customKeyId = req.body.customKeyId;
    var Sql = `UPDATE project_custom_key SET disable = 1 WHERE custom_key_id = ?`;
    try {
        await Permission.CPP(req.headers.token,  req.query.projectId);
        await asyncQuery(Sql, [customKeyId]);
        res.json({});
    } catch (error) {
       next(error)
    };
});


module.exports = router;